// Copyright 2024 Tvux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package _068

import "strings"

// blank 返回长度为n的空格字符串
func blank(n int) string {
	return strings.Repeat(" ", n)
}

func fullJustify(words []string, maxWidth int) (res []string) {
	right, n := 0, len(words)
	for {
		left := right
		sumLen := 0 // 当前行的单词长度之和
		for right < n && sumLen+len(words[right])+right-left <= maxWidth {
			// 还需要加上right-left，因为每个单词之间至少要有一个空格，这个right-left就代表单词之间的间隔数量
			sumLen += len(words[right])
			right++
		}

		if right == n {
			// 最后一行
			s := strings.Join(words[left:], " ")        // 左对齐，单词之间间隔一个空格
			res = append(res, s+blank(maxWidth-len(s))) // 补充剩余空格
			return
		}
		// 不是最后一行

		numWords := right - left
		numSpaces := maxWidth - sumLen

		if numWords == 1 {
			// 该行只有一个单词
			res = append(res, words[left]+blank(numSpaces)) // 左对齐，并补充剩余空格
			continue
		}
		// 该行不止一个单词

		avgSpaces := numSpaces / (numWords - 1)   // numWords-1表示单词的间隔数量
		extraSpaces := numSpaces % (numWords - 1) // 多出来的空格数量

		// 处理前半部分需要添加多出来的空格的部分
		s1 := strings.Join(words[left:left+extraSpaces+1], blank(avgSpaces+1))
		// 处理后半部分只需要添加平均的空格数量的部分
		s2 := strings.Join(words[left+extraSpaces+1:right], blank(avgSpaces))
		// 拼接
		res = append(res, s1+blank(avgSpaces)+s2)
	}
}
